package qeb.handheldmedical.user;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import qeb.handheldmedical.Home;
import qeb.handheldmedical.Login;
import qeb.handheldmedical.R;
import qeb.handheldmedical.Welcome;
import qeb.handheldmedical.R.layout;
import qeb.handheldmedical.approval.ApprovalOperationPatients;
import qeb.handheldmedical.dialog.MultiDialog;
import qeb.handheldmedical.exam.LineExam;
import qeb.handheldmedical.helper.WSHelper;
import qeb.handheldmedical.model.User;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.opengl.Visibility;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

/**
 * @author 作者(dugaoyi) E-mail:dugaoyi@163.com
 * @version 创建时间：2016年9月2日 下午4:35:54
 * @declaration 用户信息
 */
public class UserInfo extends Activity {
	public static final String ACTION_INTENT_TEST = "com.handheldMedical.msg";

	User usr = new User();
	private Button btn_title_back, btn_title_right, btn_switch, btn_yes,
			btn_loginOut, btn_cance;
	private TextView tv_top_title;
	private ImageView sweepIV;
	private User newusr = new User();
	private ListView ltvbq;
	private String selectBqName = "";
	private String selectBqid = "";
	private LinearLayout layout2;
	private MultiDialog checkdialog;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_info);
		usr = (User) getIntent().getSerializableExtra("userinfo");
		layout2 = (LinearLayout) findViewById(R.id.include3);
		layout2.setVisibility(View.INVISIBLE);
		ltvbq = (ListView) findViewById(R.id.ltvbq);
		tv_top_title = (TextView) findViewById(R.id.tv_top_title);
		tv_top_title.setText("我的");

		btn_switch = (Button) findViewById(R.id.btn_switch);
		btn_switch.setOnClickListener(MyOnClickListener);

		btn_switch = (Button) findViewById(R.id.btn_switch);
		btn_switch.setOnClickListener(MyOnClickListener);

		btn_yes = (Button) findViewById(R.id.btn_yes);
		btn_yes.setOnClickListener(MyOnClickListener);

		btn_cance = (Button) findViewById(R.id.btn_cance);
		btn_cance.setOnClickListener(MyOnClickListener);

		btn_title_back = (Button) findViewById(R.id.btn_title_back);
		btn_title_back.setOnClickListener(MyOnClickListener);
		btn_loginOut = (Button) findViewById(R.id.btn_loginOut);
		btn_loginOut.setOnClickListener(MyOnClickListener);

		btn_title_right = (Button) findViewById(R.id.btn_title_right);
		btn_title_right.setOnClickListener(MyOnClickListener);
		btn_title_back.setVisibility(View.GONE);
		btn_title_right.setVisibility(View.GONE);
		TextView tv_yhName = (TextView) findViewById(R.id.tv_yhName);
		tv_yhName.setText("姓名：" + usr.DNAME);
		TextView tv_yhBqname = (TextView) findViewById(R.id.tv_yhBqname);
		tv_yhBqname.setText("病区：" + usr.BQNAME);
		TextView tv_yhGh = (TextView) findViewById(R.id.tv_yhGh);
		tv_yhGh.setText("工号：" + usr.GH);

		sweepIV = (ImageView) findViewById(R.id.sweepIV);
		createQRImage(usr.GH, 400, 400);
	}

	private OnClickListener MyOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_title_back:
				finishActivity("0");
				break;
			case R.id.btn_switch:
				layout2.setVisibility(View.VISIBLE);
				switchBq();
				break;
			case R.id.btn_cance:
				layout2.setVisibility(View.GONE);
				break;
			case R.id.btn_yes:
				layout2.setVisibility(View.GONE);
				usr.BQID = selectBqid;
				usr.BQNAME = selectBqName;
				// 发送广播
				Intent intent = new Intent(ACTION_INTENT_TEST);
				intent.putExtra("userinfo", usr);
				sendBroadcast(intent);

				// finishActivity("1");
				break;
			case R.id.btn_loginOut:
				checkdialog = new MultiDialog(UserInfo.this,
						MultiDialog.DialogType.CONFIRM);
				checkdialog.setTitle("系统提醒");
				checkdialog.setMessage("您确认要退出登录吗？");
				checkdialog.setDialogGoListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						checkdialog.cancel();
						final Intent intent_back = new Intent(UserInfo.this,
								Welcome.class);
						intent_back.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						UserInfo.this.getApplicationContext().startActivity(
								intent_back);
						UserInfo.this.finish();
					}
				});
				checkdialog.show();
				break;
			}
		}

	};

	/**
	 * 关闭并返回值
	 */
	private void finishActivity(String state) {
		Intent intent = new Intent();// 数据是使用Intent返回
		intent.putExtra("userinfo", usr);// 把返回数据存入Intent
		// 列新用户信息
		if (state.equals("1")) {
			UserInfo.this.setResult(RESULT_OK, intent);// 设置返回数据
		} else {
			UserInfo.this.setResult(RESULT_CANCELED, intent);// 设置返回数据
		}
		UserInfo.this.finish();// 关闭Activity
	}

	/**
	 * 切换病区
	 */
	private void switchBq() {
		// TODO Auto-generated method stub
		// usr = (User) getIntent().getSerializableExtra("userinfo");
		// newusr = WSHelper.Login(gh, password);
		List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();

		HashMap<String, String> map = new HashMap<String, String>();
		map.put("did", usr.DID);
		map.put("typeflag", "1");
		JSONArray bqlist = WSHelper
				.getWebserviceFun("GetWardListByUserID", map);

		if (null != bqlist && bqlist.length() > 0) {

			for (int i = 0; i < bqlist.length(); i++) {
				JSONObject bqObject;
				try {
					bqObject = bqlist.getJSONObject(i);
					HashMap<String, String> h = new HashMap<String, String>();
					h.put("bqname", bqObject.getString("BQNAME"));
					h.put("bqid", bqObject.getString("BQID"));
					data.add(h);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			SimpleAdapter adapter = new SimpleAdapter(this, data,
					R.layout.bqitem, new String[] { "bqname", "bqid" },
					new int[] { R.id.chkbq, R.id.tvbqid });
			ltvbq.setAdapter(adapter);

			ltvbq.post(new Runnable() {
				@Override
				public void run() {
					setListViewItem(usr.BQID);
				}
			});

			ltvbq.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					TextView tvbqid = (TextView) view.findViewById(R.id.tvbqid);
					setListViewItem(tvbqid.getText().toString());
				}
			});

		}
	}

	/**
	 * 设置病区item
	 * 
	 * @param bqid
	 */
	public void setListViewItem(String bqid) {
		for (int i = 0; i < ltvbq.getChildCount(); i++) {
			CheckBox chkbq = (CheckBox) ltvbq.getChildAt(i).findViewById(
					R.id.chkbq);
			chkbq.setChecked(false);

			TextView tvbqid = (TextView) ltvbq.getChildAt(i).findViewById(
					R.id.tvbqid);

			if (tvbqid.getText().toString().equals(bqid)) {
				chkbq.setChecked(true);
				selectBqName = chkbq.getText().toString();
				selectBqid = bqid;
			}
		}

	}

	/**
	 * 生成二维码
	 * 
	 * @param url
	 */
	public void createQRImage(String gh, int QR_WIDTH, int QR_HEIGHT) {
		try {
			// 判断URL合法性
			if (gh == null || "".equals(gh) || gh.length() < 1) {
				return;
			}
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			// 图像数据转换，使用了矩阵转换
			BitMatrix bitMatrix = new QRCodeWriter().encode(gh,
					BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
			int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
			// 下面这里按照二维码的算法，逐个生成二维码的图片，
			// 两个for循环是图片横列扫描的结果
			for (int y = 0; y < QR_HEIGHT; y++) {
				for (int x = 0; x < QR_WIDTH; x++) {
					if (bitMatrix.get(x, y)) {
						pixels[y * QR_WIDTH + x] = 0xff000000;
					} else {
						pixels[y * QR_WIDTH + x] = 0xffffffff;
					}
				}
			}
			// 生成二维码图片的格式，使用ARGB_8888
			Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
					Bitmap.Config.ARGB_8888);
			bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
			// 显示到一个ImageView上面
			sweepIV.setImageBitmap(bitmap);
		} catch (WriterException e) {
			e.printStackTrace();
		}
	}
}
